package com.jiyun.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jiyun.entity.Dept;
import com.jiyun.entity.Station;
import com.jiyun.entity.User;
import com.jiyun.entity.UserRole;
import com.jiyun.service.IDeptService;
import com.jiyun.service.IStationService;
import com.jiyun.service.IUserRoleService;
import com.jiyun.service.IUserService;
import com.jiyun.vo.UserVo;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  控制层
 * </p>
 *
 * @author 聪哥哥
 * @since 2023-05-05
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IUserService userService;

    @Autowired
    IUserRoleService userRoleService;

    /**
     * 添加接口
     */
    @RequestMapping("/add")
    public void addUser(@RequestBody UserVo userVo){

        User user = new User();
        BeanUtils.copyProperties(userVo,user);
        user.setCreateTime(new Date());

        userService.save(user);

        for (String rid : userVo.getRids().split(",")) {
            UserRole userRole = new UserRole();
            userRole.setRid(Integer.parseInt(rid));
            userRole.setUid(user.getId());
            userRoleService.save(userRole);
        }
    }

    /**
     * 修改接口
     */
    @RequestMapping("/update")
    public void updateUser(@RequestBody User user){
        userService.updateById(user);
    }

    /**
     * 单个删除接口
     */
    @RequestMapping("/deleteOne")
    public void deleteOne(@RequestParam Integer id){
        userService.removeById(id);
    }

    /**
     * 批量删除接口
     * 前台ajax参数ids传入示例：1,2,3  (英文逗号分隔的字符串)
     */
    @RequestMapping("/deleteBatch")
    public void deleteBatch(@RequestParam List<Integer> ids){
        userService.removeByIds(ids);
    }

    /**
     * 根据id查询实体接口
     */
    @RequestMapping("/findById")
    public User findById(@RequestParam Integer id){
        return userService.getById(id);
    }

    /**
     * 查询所有接口
     */
    @RequestMapping("/findAll")
    public List<User> findAll(){
        return userService.list();
    }


    @Autowired
    IDeptService deptService;
    /**
     * 分页查询接口
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     * 重要提示：启用分页功能必须在配置类中添加mybatis-plus分页的拦截器
     */
    @RequestMapping("/findPage")
    public Page<UserVo> findPage(@RequestParam Integer page, @RequestParam Integer pageSize, @RequestBody UserVo userVo){
        /**
         1、先把要查询的部门数据传到后台
         2、根据这个部门id组装所有子级的id集合
         3、sql中用in查询
         */

        if(userVo.getDid()!=null){
            List<Dept> deptList = deptService.list();

            ArrayList<Integer> ids = new ArrayList<>();
            ids.add(userVo.getDid());
            findIdsByPid(deptList,userVo.getDid(),ids);//查找这个pid的子部门信息

            System.out.println("组装好的部门id集合为："+ids);

            userVo.setDids(ids);

        }


        return userService.findPage(page,pageSize,userVo);
    }


    public void findIdsByPid(List<Dept> deptList,Integer pid,List<Integer> ids){

        for (Dept dept : deptList) {
            if(dept.getPid().equals(pid)){//找到当前pid的子部门
                ids.add(dept.getId());//找到之后，把子部门的id放到ids集合中
                findIdsByPid(deptList,dept.getId(),ids);
            }
        }
    }

    @RequestMapping("exportData")
    public void exportData(HttpServletResponse response) throws Exception{


        List<UserVo> userVoList = userService.findAllUserVo();

        XSSFWorkbook workbook = new XSSFWorkbook();
        XSSFSheet sheet = workbook.createSheet();

        int rowNum = 0;
        XSSFRow row = sheet.createRow(rowNum++);

        int cellNum = 0;
        XSSFCell cell = row.createCell(cellNum++);
        cell.setCellValue("ID");
        cell = row.createCell(cellNum++);
        cell.setCellValue("登录名称");
        cell = row.createCell(cellNum++);
        cell.setCellValue("用名称");
        cell = row.createCell(cellNum++);
        cell.setCellValue("部门");
        cell = row.createCell(cellNum++);
        cell.setCellValue("手机号");
        cell = row.createCell(cellNum++);
        cell.setCellValue("状态");
        cell = row.createCell(cellNum++);
        cell.setCellValue("时间");


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        for (UserVo userVo : userVoList) {
            row = sheet.createRow(rowNum++);
            cellNum = 0;
            cell = row.createCell(cellNum++);
            cell.setCellValue(userVo.getId());
            cell = row.createCell(cellNum++);
            cell.setCellValue(userVo.getAccount());
            cell = row.createCell(cellNum++);
            cell.setCellValue(userVo.getName());
            cell = row.createCell(cellNum++);
            cell.setCellValue(userVo.getDname());
            cell = row.createCell(cellNum++);
            cell.setCellValue(userVo.getPhone());
            cell = row.createCell(cellNum++);
            cell.setCellValue(userVo.getState());
            cell = row.createCell(cellNum++);
            cell.setCellValue(sdf.format(userVo.getCreateTime()));

        }


        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户列表.xlsx", "UTF-8"));
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");
        workbook.write(response.getOutputStream());
    }


    @RequestMapping("findAllUser4Choose")
    public List<User> findAllUser4Choose(Integer rid){
        return userService.findAllUser4Choose(rid);
    }


    @Autowired
    IStationService stationService;
    @RequestMapping("importData")
    public void importData(MultipartFile file) throws Exception{
        System.out.println(file.getOriginalFilename());


        XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

        XSSFSheet sheet = workbook.getSheetAt(0);


        int lastRowNum = sheet.getLastRowNum();

        for (int i = 1; i <= lastRowNum; i++) {
            XSSFRow row = sheet.getRow(i);

            int cellNum = 0;

            //姓名	账号	部门	手机号	邮箱	密码	性别	状态	岗位	备注
            String name = row.getCell(cellNum++).getStringCellValue();
            String account = row.getCell(cellNum++).getStringCellValue();
            String dname = row.getCell(cellNum++).getStringCellValue();
            String phone = row.getCell(cellNum++).getStringCellValue();
            String email = row.getCell(cellNum++).getStringCellValue();
            String password = row.getCell(cellNum++).getStringCellValue();
            String sex = row.getCell(cellNum++).getStringCellValue();
            String state = row.getCell(cellNum++).getStringCellValue();
            String snames = row.getCell(cellNum++).getStringCellValue();
            String remark = row.getCell(cellNum++).getStringCellValue();

            User user = new User();
            user.setName(name);
            user.setAccount(account);
            user.setPhone(phone);
            user.setEmail(email);
            user.setPassword(password);
            user.setSex(sex);
            user.setState(state);
            user.setRemark(remark);

            LambdaQueryWrapper<Dept> deptLambdaQueryWrapper = new LambdaQueryWrapper<>();
            deptLambdaQueryWrapper.eq(Dept::getName,dname);
            Dept dept = deptService.getOne(deptLambdaQueryWrapper);
            user.setDid(dept.getId());


            String sids = "";
            for (String sname : snames.split(",")) {
                LambdaQueryWrapper<Station> stationLambdaQueryWrapper = new LambdaQueryWrapper<>();
                stationLambdaQueryWrapper.eq(Station::getName,sname);
                Station station = stationService.getOne(stationLambdaQueryWrapper);
                sids+=station.getId()+",";
            }
            sids = sids.substring(0,sids.length()-1);
            user.setSids(sids);


            user.setCreateTime(new Date());
            userService.save(user);

        }



    }
}
